package com.neo.tiny.report.jimu.security;

import cn.hutool.core.bean.BeanUtil;
import com.neo.tiny.oauth.api.Oauth2TokenApi;
import com.neo.tiny.secrity.util.SecurityUtils;
import com.neo.tiny.token.context.TokenAuthentication;
import com.neo.tiny.token.store.OAuth2AccessToken;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Description: 积木报表配置token
 * @Author: yqz
 * @CreateDate: 2022/12/10 22:58
 */
@Slf4j
@AllArgsConstructor
public class JimuReportTokenServiceImpl implements JmReportTokenServiceI {

    private final Oauth2TokenApi oauth2TokenApi;

    private final UserDetailsService userDetailsService;

    @Override
    public String getUsername(String accessToken) {

        Long userId = SecurityUtils.getUserId();
        return userId != null ? String.valueOf(userId) : null;
    }

    @Override
    public Boolean verifyToken(String accessToken) {
        OAuth2AccessToken oAuth2AccessToken = oauth2TokenApi.checkAccessToken(accessToken);

        if (BeanUtil.isEmpty(oAuth2AccessToken)) {
            return false;
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(oAuth2AccessToken.getUserName());
        TokenAuthentication tokenAuthentication = new TokenAuthentication(userDetails, userDetails,
                oAuth2AccessToken.getUserType(), oAuth2AccessToken.getClientId());
        tokenAuthentication.setAuthenticated(true);
        tokenAuthentication.setAuthorities(userDetails.getAuthorities());
        tokenAuthentication.setScopes(oAuth2AccessToken.getScopes());
        log.info("已认证的用户：{}", oAuth2AccessToken.getUserName());
        //重新把认证添加到上下文中
        SecurityContextHolder.getContext().setAuthentication(tokenAuthentication);

        return true;
    }
}
